package com.ft.turorial.security.service;

import com.ftqh.security.user.domain.User;
import com.ftqh.security.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2016/12/27
 * \* Time: 18:21
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if(null == user){
            throw new UsernameNotFoundException("Could not find user " + username);
        }
        //创建角色对象后，就在此获取角色列表
        //Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER_ROLE");
        return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);

    }
}
